import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/song.dart';
import '../widgets/song_list_widget.dart';
import '../services/music_player_service.dart';
import '../services/music_api_service.dart';
import '../models/music_source.dart';
import '../widgets/mini_player_widget.dart';
import '../widgets/player_sheet_widget.dart';
import '../utils/util.dart';

class RankingScreen extends StatefulWidget {
  final String rankingType;
  final String title;

  const RankingScreen({
    super.key,
    required this.rankingType,
    required this.title,
  });

  @override
  State<RankingScreen> createState() => _RankingScreenState();
}

class _RankingScreenState extends State<RankingScreen> {
  List<Song> _songs = [];
  bool _isLoading = true;
  String _error = '';
  final ScrollController _wideController = ScrollController();
  int? _hoveredIndex;

  @override
  void initState() {
    super.initState();
    _loadRankingSongs();
  }

  Future<void> _loadRankingSongs() async {
    try {
      setState(() {
        _isLoading = true;
        _error = '';
      });

      final apiService = MusicApiService();
      final results = await apiService.getRankingSongs(
        rankingType: widget.rankingType,
        source: MusicSource.netease,
        count: 50,
      );
      
      setState(() {
        _songs = results;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _error = '加载失败: $e';
        _isLoading = false;
      });
    }
  }

  void _onSongTap(Song song, int index) {
    final playerService = Provider.of<MusicPlayerService>(context, listen: false);
    playerService.setPlaylist(_songs, startIndex: index);
  }

  @override
  void dispose() {
    _wideController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          widget.title,
          style: const TextStyle(fontWeight: FontWeight.bold),
        ),
        backgroundColor: Theme.of(context).colorScheme.surface,
        foregroundColor: Theme.of(context).colorScheme.onSurface,
        actions: [
          IconButton(
            onPressed: _loadRankingSongs,
            icon: const Icon(Icons.refresh),
            tooltip: '刷新',
          ),
        ],
      ),
      body: _buildBody(),
      // 底部迷你播放器：仅在有正在播放的歌曲时显示
      bottomNavigationBar: Consumer<MusicPlayerService>(
        builder: (context, playerService, child) {
          if (playerService.currentSong == null) {
            return const SizedBox.shrink();
          }
          return MiniPlayerWidget(onTap: _showPlayerSheet);
        },
      ),
    );
  }

  Widget _buildBody() {
    if (_isLoading) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 16),
            Text('加载排行榜中...'),
          ],
        ),
      );
    }

    if (_error.isNotEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              width: 120,
              height: 120,
              decoration: BoxDecoration(
                color: Theme.of(context).colorScheme.error.withOpacity(0.1),
                borderRadius: BorderRadius.circular(60),
              ),
              child: Icon(
                Icons.error_outline,
                size: 60,
                color: Theme.of(context).colorScheme.error,
              ),
            ),
            const SizedBox(height: 24),
            Text(
              '加载失败',
              style: Theme.of(context).textTheme.headlineSmall?.copyWith(
                fontWeight: FontWeight.w600,
              ),
            ),
            const SizedBox(height: 8),
            Text(
              _error,
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                color: Theme.of(context).colorScheme.onSurfaceVariant,
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 32),
            ElevatedButton.icon(
              onPressed: _loadRankingSongs,
              icon: const Icon(Icons.refresh),
              label: const Text('重试'),
            ),
          ],
        ),
      );
    }

    final isWide = CommonUtils.isWideScreen(context);
    if (isWide) {
      return Column(
        children: [
          // 列头
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.surface,
              border: Border(
                bottom: BorderSide(color: Theme.of(context).colorScheme.outline.withOpacity(0.4)),
              ),
            ),
            child: Row(
              children: [
                const SizedBox(width: 28, child: Text('#', textAlign: TextAlign.center, style: TextStyle(fontSize: 11, color: Colors.black54))),
                const SizedBox(width: 6),
                Expanded(
                  flex: 3,
                  child: Text('歌名', style: Theme.of(context).textTheme.bodySmall?.copyWith(fontWeight: FontWeight.w600, fontSize: 12)),
                ),
                Expanded(
                  flex: 2,
                  child: Text('歌手', style: Theme.of(context).textTheme.bodySmall?.copyWith(fontWeight: FontWeight.w600, fontSize: 12)),
                ),
                Expanded(
                  flex: 2,
                  child: Text('专辑', style: Theme.of(context).textTheme.bodySmall?.copyWith(fontWeight: FontWeight.w600, fontSize: 12)),
                ),
                Expanded(
                  flex: 1,
                  child: Text('音源', style: Theme.of(context).textTheme.bodySmall?.copyWith(fontWeight: FontWeight.w600, fontSize: 12)),
                ),
              ],
            ),
          ),
          Expanded(
            child: Scrollbar(
              controller: _wideController,
              thumbVisibility: true,
              thickness: 6,
              radius: const Radius.circular(6),
              child: _buildWideSongList(),
            ),
          ),
        ],
      );
    }

    // 窄屏：保持原有列表样式
    return SongListWidget(
      songs: _songs,
      onSongTap: _onSongTap,
      showRanking: true,
    );
  }

  Widget _buildWideSongList() {
    final theme = Theme.of(context);
    final outline = theme.colorScheme.outline.withOpacity(0.35);
    return ListView.builder(
      controller: _wideController,
      primary: false,
      itemCount: _songs.length,
      itemBuilder: (context, index) {
        final song = _songs[index];
        final hovered = _hoveredIndex == index;
        final bgColor = hovered
            ? theme.colorScheme.surfaceContainerHighest
            : (index % 2 == 0 ? theme.colorScheme.surface : Colors.transparent);
        return MouseRegion(
          onEnter: (_) => setState(() => _hoveredIndex = index),
          onExit: (_) => setState(() => _hoveredIndex = null),
          child: Material(
            color: bgColor,
            child: InkWell(
              onTap: () => _onSongTap(song, index),
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                decoration: BoxDecoration(
                  border: Border(bottom: BorderSide(color: outline, width: 0.4)),
                ),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    SizedBox(
                      width: 28,
                      child: Text(
                        '${index + 1}',
                        textAlign: TextAlign.center,
                        style: TextStyle(fontSize: 11, color: theme.colorScheme.onSurfaceVariant),
                      ),
                    ),
                    const SizedBox(width: 6),
                    Expanded(
                      flex: 3,
                      child: Tooltip(
                        message: song.name,
                        waitDuration: const Duration(milliseconds: 600),
                        child: Text(
                          song.name,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(fontSize: 14, color: theme.colorScheme.onSurface),
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 2,
                      child: Tooltip(
                        message: song.artistsString,
                        waitDuration: const Duration(milliseconds: 600),
                        child: Text(
                          song.artistsString,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(fontSize: 13, color: theme.colorScheme.onSurfaceVariant),
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 2,
                      child: Tooltip(
                        message: song.album,
                        waitDuration: const Duration(milliseconds: 600),
                        child: Text(
                          song.album,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(fontSize: 13, color: theme.colorScheme.onSurfaceVariant),
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 1,
                      child: Align(
                        alignment: Alignment.centerLeft,
                        child: _buildSourceChip(MusicSource.fromString(song.source)),
                      ),
                    ),
                    const SizedBox(width: 6),
                    IconButton(
                      icon: Icon(Icons.play_arrow, color: theme.colorScheme.primary, size: 18),
                      tooltip: '播放',
                      onPressed: () => _onSongTap(song, index),
                      style: ButtonStyle(
                        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        padding: WidgetStateProperty.all(const EdgeInsets.all(6)),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildSourceChip(MusicSource source) {
    final theme = Theme.of(context);
    final color = theme.colorScheme.primary;
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
      decoration: BoxDecoration(
        color: color.withOpacity(0.08),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: color.withOpacity(0.16)),
      ),
      child: Text(
        source.displayName,
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(fontSize: 10, color: color, fontWeight: FontWeight.w600),
      ),
    );
  }

  void _showPlayerSheet() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      constraints: const BoxConstraints(
        maxWidth: double.infinity,
        maxHeight: double.infinity,
      ),
      useSafeArea: true,
      builder: (context) => const PlayerSheetWidget(),
    );
  }
}
